package message

import (
	"github.com/gin-gonic/gin"
	"oa-rest/common"
	"strconv"
)

// GetRobotDocsHandler 获取机器人文档处理器
func (s *MessageService) GetRobotDocsHandler(c *gin.Context) {
	var res common.Response
	var req RobotDocsRequest

	// 绑定查询参数
	if err := c.ShouldBindQuery(&req); err != nil {
		res.Code = 400
		res.Msg = "请求参数错误: " + err.Error()
		res.Format(c)
		return
	}

	// 设置默认分页参数
	if req.PageNum <= 0 {
		req.PageNum = 1
	}
	if req.PageSize <= 0 {
		req.PageSize = 10
	}

	// 查询文档消息
	messages, total, err := s.dao.GetRobotDocs(c.Request.Context(), &req)
	if err != nil {
		res.Code = 500
		res.Msg = "查询文档消息失败: " + err.Error()
		res.Format(c)
		return
	}

	// 获取未读数量
	unread, err := s.dao.GetRobotUnreadCount(c.Request.Context(), req.RobotId)
	if err != nil {
		res.Code = 500
		res.Msg = "查询未读数量失败: " + err.Error()
		res.Format(c)
		return
	}

	// 构建响应数据
	response := RobotDocsResponse{
		Messages: messages,
		Total:    total,
		PageNum:  req.PageNum,
		PageSize: req.PageSize,
		Unread:   unread,
	}

	res.Data = response
	res.Format(c)
}

// UpdateMessageStatusHandler 更新消息状态处理器
func (s *MessageService) UpdateMessageStatusHandler(c *gin.Context) {
	var res common.Response
	var req Message

	if err := c.ShouldBindJSON(&req); err != nil {
		res.Format(c, err.Error())
		return
	}
	if req.Id == 0 || req.Status == 0 {
		res.Format(c, "params error")
		return
	}

	// 更新状态
	err := s.dao.UpdateMessageStatus(c.Request.Context(), req.Id, req.Status)
	if err != nil {
		res.Code = 500
		res.Msg = "更新消息状态失败: " + err.Error()
		res.Format(c)
		return
	}

	res.Msg = "消息状态更新成功"
	res.Format(c)
}

// BatchUpdateMessageStatusHandler 批量更新消息状态处理器
func (s *MessageService) BatchUpdateMessageStatusHandler(c *gin.Context) {
	var res common.Response

	// 获取机器人ID和状态
	robotId := c.Query("robotId")
	if robotId == "" {
		res.Code = 400
		res.Msg = "机器人ID不能为空"
		res.Format(c)
		return
	}

	status, err := strconv.ParseInt(c.Query("status"), 10, 32)
	if err != nil || (status != 1 && status != 2) {
		res.Code = 400
		res.Msg = "无效的状态参数，只能是1（未读）或2（已读）"
		res.Format(c)
		return
	}

	// 批量更新状态
	rowsAffected, err := s.dao.BatchUpdateMessageStatus(c.Request.Context(), robotId, int32(status))
	if err != nil {
		res.Code = 500
		res.Msg = "批量更新消息状态失败: " + err.Error()
		res.Format(c)
		return
	}

	res.Msg = "批量更新消息状态成功"
	res.Data = gin.H{
		"updatedCount": rowsAffected,
	}
	res.Format(c)
}

// RegisterRobotDocsRoutes 注册机器人文档相关路由
func (s *MessageService) RegisterRobotDocsRoutes(group *gin.RouterGroup) {
	// 获取机器人文档列表
	group.GET("/message/getRobotDocs", s.GetRobotDocsHandler)

	// 更新单个消息状态
	group.POST("/message/updStatus", s.UpdateMessageStatusHandler)

	// 批量更新消息状态
	group.PUT("/message/batchStatus", s.BatchUpdateMessageStatusHandler)
}
